package com.cxq.stack;

import sun.reflect.generics.tree.VoidDescriptor;

import javax.sound.midi.VoiceStatus;
import java.util.Arrays;

public class ArrayStackDemo {
    public static void main(String[] args){
        ArrayStack arrayStack = new ArrayStack(5);
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        arrayStack.push(4);
        arrayStack.push(5);
        arrayStack.show();
        arrayStack.pop();
        arrayStack.show();
    }
}

class ArrayStack{
    private int maxSize;//栈的大小
    private int[] stack;//数组，数组模拟栈，数据就放在该数组中
    private int top; // top表示栈顶，初始化为-1

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
        this.top  = -1;
    }

    //栈满
    public boolean isFull(){
        return top == maxSize-1;
    }

    //栈空
    public boolean isEmpty(){
        return top == -1;
    }

    //入栈
    public void push(int value){
        if(isFull()){
            System.out.println("栈满！");
            return;
        }
        top++;
        stack[top] = value;
    }

    //出栈-pop 将栈顶的数据返回
    public int pop(){
        //先判断栈是否空
        if(isEmpty()){
            //抛出异常
            throw new RuntimeException("栈空，没有数据！");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //遍历栈
    public void show(){
        if(isEmpty()){
            System.out.println("栈空，没有数据！");
            return;
        }
        //需要从栈顶开始显示数据
        for(int i = top;i>=0;i--){
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }


}